<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Jobs\SendEmail;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Facades\Redis;
use Overtrue\EasySms\EasySms;
use Overtrue\EasySms\Exceptions\NoGatewayAvailableException;
use Validator;

class UserController extends Controller {
	/**
	 * 发送验证码
	 * @param  $mobile     [请求手机号]
	 * @param  $type    [1 app,2 pc]
	 * @param  $from    [1 注册,2 修改密码]
	 * @return $请求返回结果(array)
	 */
	public function sendMessage(Request $request) {
		$data = $request->all();
		if (empty($data)) {
			return response()->json(['code' => 400, 'msg' => '系统异常', 'data' => '']);
		}
		$mobile = $data['mobile'];
		$type = $data['type'];
		$from = $data['from'];
		if (!isset($mobile{10})) {
			return response()->json(['code' => 400, 'msg' => '手机号格式错误', 'data' => '']);
		}
		$use = User::where('mobile', $mobile)->first();
		if (($from == 1) && !empty($use)) {
			return response()->json(['code' => 400, 'msg' => '手机号已注册', 'data' => '']);
		}
		if ($from == 2 && empty($use)) {
			return response()->json(['code' => 400, 'msg' => '手机号未注册', 'data' => '']);
		}
		$config = Config::get('info.message_config');
		$easySms = new EasySms($config);
		$code = rand(1000, 9999);
		$redMobile = Redis::exists($mobile . 'code');
		if ($redMobile) {
			$redCode = Redis::get($mobile . 'code');
			Redis::del($mobile . 'code');
		}
		$redTime = Redis::exists($mobile . 'time');
		if ($redTime) {
			$redTime = Redis::get($mobile . 'time');
			Redis::del($mobile . 'time');
		}
		try {
			$result = $easySms->send($mobile, [
				'content' => '您的验证码${code}，该验证码5分钟内有效，请勿泄漏于他人！',
				'template' => 'SMS_126570108',
				'data' => [
					'code' => $code,
				],
			]);
		} catch (NoGatewayAvailableException $e) {
			return response()->json(['code' => 200, 'msg' => '短信发送失败', 'data' => '']);
		}
		Redis::setex($mobile . 'code', 300, $code);
		Redis::setex($mobile . 'time', 300, time());
		if ($result['aliyun']['status'] == 'success') {
			return response()->json(['code' => 200, 'msg' => '短信发送成功', 'data' => '']);
		} else {
			return response()->json(['code' => 400, 'msg' => '由于您操作次数过多，5分钟后再进行操作', 'data' => '']);
		}
	}
	/**
	 * 验证码验证
	 * @param  $mobile     [请求手机号]
	 * @param  $code   [验证码]
	 */
	public function codeVerify(Request $request) {
		$data = $request->all();
		if (empty($data)) {
			return response()->json(['code' => 400, 'msg' => '系统异常', 'data' => '']);
		}
		$mobile = $data['mobile'];
		$postCode = $data['code'];
		$nowTime = time();
		$redisCode = Redis::get($mobile . 'code');
		$redisTime = Redis::get($mobile . 'time');
		$timeApart = $nowTime - $redisTime;
		if ($timeApart < 0 || $timeApart > 300 || ($redisCode != $postCode)) {
			return response()->json(['code' => 400, 'msg' => '验证码错误或失效', 'data' => '']);
		}
		Redis::del($mobile . 'code');
		Redis::del($mobile . 'time');
		$info = str_random(20);
		Redis::setex($mobile . 'info', 3600, $info);
		return response()->json(['code' => 200, 'msg' => '验证成功', 'data' => ['info' => $info]]);
	}
	/**
	 * 注册
	 * @param  $mobile     [请求手机号]
	 * @param  $code   [pc 验证码]
	 * @param  $info   [app 验证字符创]
	 * @param  $from  [1app,2pc]
	 * @param  $pwd  [密码]
	 *
	 */
	public function register(Request $request) {
		$data = $request->all();
		if (empty($data)) {
			return response()->json(['code' => 400, 'msg' => '系统异常', 'data' => ['mobileToken' => '', 'pcToken' => '', 'uid' => '']]);
		}
		$mobile = $data['mobile'];
		$code = $data['code'];
		$info = $data['info'];
		$pwd = $data['pwd'];
		$from = $data['from'];
		$use = User::where('mobile', $mobile)->first();
		if (!empty($use)) {
			return response()->json(['code' => 400, 'msg' => '手机号已注册', 'data' => ['mobileToken' => '', 'pcToken' => '', 'uid' => '']]);
		}
		$time = time();
		if ($from == 1) {
			if (empty($mobile) || empty($info) || empty($pwd)) {
				return response()->json(['code' => 400, 'msg' => '系统异常', 'data' => ['mobileToken' => '', 'pcToken' => '', 'uid' => '']]);
			}
			$redisInfo = Redis::get($mobile . 'info');
			if ($info != $redisInfo) {
				return response()->json(['code' => 400, 'msg' => '非法操作', 'data' => ['mobileToken' => '', 'pcToken' => '', 'uid' => '']]);
			}
		}
		if ($from == 2) {
			if (empty($mobile) || empty($code) || empty($pwd)) {
				return response()->json(['code' => 400, 'msg' => '系统异常', 'data' => ['mobileToken' => '', 'pcToken' => '', 'uid' => '']]);
			}
			$redisInfo = Redis::get($mobile . 'code');
			$redisTime = Redis::get($mobile . 'time');
			$apart = $time - $redisTime;
			if ($apart < 0 || $apart > 300) {
				return response()->json(['code' => 400, 'msg' => '验证码已过期', 'data' => ['mobileToken' => '', 'pcToken' => '', 'uid' => '']]);
			}
			if ($code != $redisInfo) {
				return response()->json(['code' => 400, 'msg' => '验证码错误', 'data' => ['mobileToken' => '', 'pcToken' => '', 'uid' => '']]);
			}
		}
		Redis::del($mobile . 'code');
		Redis::del($mobile . 'time');
		$salt = str_random(6);
		$password = md5($pwd . $salt);
		$pcToken = str_random(20);
		$appToken = str_random(20);
		$userId = DB::table('users')->insertGetId(
			['mobile' => $mobile, 'password' => $password, 'image' => 'image/all.png', 'salt' => $salt, 'pc_token' => $pcToken, 'name' => $mobile, 'mobile_token' => $appToken, 'updated_at' => $time, 'created_at' => $time, 'accid' => '', 'acc_token' => '']
		);
		$user = User::find($userId);
		$accessToken = $user->createToken('token');
		$token = $accessToken->accessToken;
		$tokenInfo = $accessToken->token . '#attributes';
		$res = str_replace('#attributes', '', $tokenInfo);
		$tokenId = json_decode($res, true)['id'];
		if ($from == 1) {
			$userUp = User::where('id', $user->id)
				->update(['mobile_token' => $tokenId, 'updated_at' => time()]);
			DB::table('oauth_access_tokens')->where('id', $tokenId)->update(['expires_at' => date('Y-m-d H:i:s', strtotime('+3 days'))]);
		}
		if ($from == 2) {
			$userUp = User::where('id', $user->id)
				->update(['pc_token' => $tokenId, 'updated_at' => time()]);
			DB::table('oauth_access_tokens')->where('id', $tokenId)->update(['expires_at' => date('Y-m-d H:i:s', strtotime('+2 hours'))]);
		}
		if (empty($userUp)) {
			return response()->json(['code' => 400, 'msg' => '注册失败', 'data' => ['mobileToken' => '', 'pcToken' => '', 'uid' => '']]);
		}
		$list = DB::table('staff')->where(['mobile' => $mobile, 'status' => 0])->count();
		if ($list == 0) {
			$num = 0;
		} else {
			$num = 1;
		}
		return response()->json(['code' => 200, 'msg' => '注册成功', 'data' => ['mobileToken' => $token, 'pcToken' => $token, 'uid' => $userId, 'num' => $num]]);
	}

	/**
	 * 登录
	 * @param  $mobile    [手机号]
	 * @param  $password   [密码]
	 * * @param  $type   [密码]
	 */
	public function login(Request $request) {
		$data = $request->all();
		if (empty($data)) {
			return response()->json(['code' => 400, 'msg' => '系统异常', 'data' => ['userId' => '', 'companyId' => '']]);
		}
		$mobile = $data['mobile'];
		$pwd = $data['pwd'];
		$type = $data['from'];
		$userInfo = User::where('mobile', '=', $mobile)->first();
		if (empty($userInfo)) {
			return response()->json(['code' => 400, 'msg' => '用户未注册', 'data' => ['userId' => '', 'companyId' => '']]);
		}
		$device = $this->getDevice();
		if (!$device) {
			$userInfo->company_id = $userInfo->appcompany_id;
		}
		$password = md5($pwd . $userInfo->salt);
		if ($password != $userInfo->password) {
			return response()->json(['code' => 400, 'msg' => '密码错误', 'data' => ['userId' => '', 'companyId' => '']]);
		}
		$staff = DB::table('staff')->where(['company_id' => $userInfo->company_id, 'mobile' => $mobile, 'status' => 0])->first();
		if ((!empty($userInfo->company_id) || !empty($userInfo->appcompany_id)) && empty($staff)) {
			$userInfo->company_id = 0;
			if ($this->getDevice()) {
				DB::table('users')->where('id', $userInfo->id)->update(['updated_at' => time(), 'company_id' => 0]);
			} else {
				DB::table('users')->where('id', $userInfo->id)->update(['updated_at' => time(), 'appcompany_id' => 0]);
			}
		}
		$accessToken = $userInfo->createToken('token');
		$token = $accessToken->accessToken;
		$tokenInfo = $accessToken->token . '#attributes';
		$res = str_replace('#attributes', '', $tokenInfo);
		$tokenId = json_decode($res, true)['id'];
		if ($type == 1) {
			$userUp = DB::table('users')
				->where('id', $userInfo->id)
				->update(['mobile_token' => $tokenId, 'updated_at' => time()]);
			DB::table('oauth_access_tokens')->where('id', $userInfo->mobile_token)->delete();
			DB::table('oauth_access_tokens')->where('id', $tokenId)->update(['expires_at' => date('Y-m-d H:i:s', strtotime('+3 days'))]);
		}
		if ($type == 2) {
			$userUp = DB::table('users')
				->where('id', $userInfo->id)
				->update(['pc_token' => $tokenId]);
			DB::table('oauth_access_tokens')->where('id', $userInfo->pc_token)->delete();
			DB::table('oauth_access_tokens')->where('id', $tokenId)->update(['expires_at' => date('Y-m-d H:i:s', strtotime('+2 hours'))]);
		}
		if (empty($userUp)) {
			return response()->json(['code' => 400, 'msg' => '登录失败', 'data' => ['userId' => '', 'companyId' => '', 'name' => "", 'token' => $token]]);
		}
		$list = DB::table('staff')->where(['mobile' => $mobile, 'status' => 0])->count();
		if ($list == 0) {
			$num = 0;
		} else {
			$num = 1;
		}
		return response()->json(['code' => 200, 'msg' => '登录成功', 'data' => ['userId' => $userInfo->id, 'companyId' => $userInfo->company_id, 'name' => $userInfo->name, 'token' => $token, 'num' => $num]]);
	}
	/**
	 * 忘记密码
	 * @param  $mobile    [手机号]
	 * @param  $password   [密码]
	 * @param  $info   [下一步返回的字符创]
	 * @param  $type   [1APP,2PC]
	 */
	public function upAssword(Request $request) {
		$validator = Validator::make($request->all(), User::$rules, User::$message);
		if ($validator->fails()) {
			return response()->json(['code' => 400, 'msg' => $validator->errors()->first(), 'data' => '']);
		}
		$data = $request->all();
		$pwd = $data['pwd'];
		$mobile = $data['mobile'];
		$info = $data['info'];
		$from = $data['from'];
		$salt = str_random(6);
//        $type = $data['type'];
		$password = md5($pwd . $salt);
		$redisInfo = Redis::get($mobile . 'info');
		if ($info != $redisInfo) {
			return response()->json(['code' => 400, 'msg' => '非法操作', 'data' => '']);
		}
		$userInfo = User::where('mobile', '=', $mobile)->first();
		if (empty($userInfo)) {
			return response()->json(['code' => 400, 'msg' => '手机号未注册', 'data' => '']);
		}
		$device = $this->getDevice();
		if (!$device) {
			$userInfo->company_id = $userInfo->appcompany_id;
		}
		$staff = DB::table('staff')->where(['company_id' => $userInfo->company_id, 'mobile' => $mobile, 'status' => 0])->first();
		if ((!empty($userInfo->company_id) || !empty($userInfo->appcompany_id)) && empty($staff)) {
			$userInfo->company_id = 0;
			if ($this->getDevice()) {
				DB::table('users')->where('id', $userInfo->id)->update(['updated_at' => time(), 'company_id' => 0]);
			} else {
				DB::table('users')->where('id', $userInfo->id)->update(['updated_at' => time(), 'appcompany_id' => 0]);
			}
		}
		DB::table('oauth_access_tokens')->where('user_id', $userInfo->id)->delete();
		$accessToken = $userInfo->createToken('token');
		$token = $accessToken->accessToken;
		$tokenInfo = $accessToken->token . '#attributes';
		$res = str_replace('#attributes', '', $tokenInfo);
		$tokenId = json_decode($res, true)['id'];
		if ($from == 1) {
			$userUp = User::where('id', $userInfo->id)
				->update(['mobile_token' => $tokenId, 'password' => $password, 'salt' => $salt, 'updated_at' => time()]);
			DB::table('oauth_access_tokens')->where('id', $tokenId)->update(['expires_at' => date('Y-m-d H:i:s', strtotime('+3 days'))]);
		}
		if ($from == 2) {
			$userUp = User::where('id', $userInfo->id)
				->update(['pc_token' => $tokenId, 'password' => $password, 'salt' => $salt, 'updated_at' => time()]);
			DB::table('oauth_access_tokens')->where('id', $tokenId)->update(['expires_at' => date('Y-m-d H:i:s', strtotime('+2 hours'))]);
		}
		if (empty($userUp)) {
			return response()->json(['code' => 400, 'msg' => '密码修改失败', 'data' => []]);
		}
		$list = DB::table('staff')->where(['mobile' => $mobile, 'status' => 0])->count();
		if ($list == 0) {
			$num = 0;
		} else {
			$num = 1;
		}
		return response()->json(['code' => 200, 'msg' => '密码修改成功', 'data' => ['userId' => $userInfo->id, 'companyId' => $userInfo->company_id, 'name' => $userInfo->name, 'token' => $token, 'num' => $num]]);
	}
	/**
	 *  消息详情
	 * @param  $msgId     [消息ID]
	 * @param  $type       [类型]
	 * @return $请求返回结果(json)
	 */
	public function msgInfo(Request $request) {
		$msgId = $request->input('id');
		$type = $request->input('type');
		$info = DB::table('systemsg_create')->where('id', $msgId)->first();
		$name = $info->name;
		$time = $info->updated_at;
		switch ($type) {
		case 1:
			$title = $info->title_one;
			$content = $info->content_one;
			break;
		case 2:
			$title = $info->title_two;
			$content = $info->content_two;
			break;
		case 3:
			$title = $info->title_three;
			$content = $info->content_three;
			break;
		case 4:
			$title = $info->title_four;
			$content = $info->content_four;
			break;
		default:
			$data = ['title' => '', 'content' => ''];
//                return  response()->json(['code'=>200,'msg'=>'请求成功','data'=>['title'=>'','content'=>'']]);
			echo $request->input('callback') . '(' . json_encode($data) . ')';
			break;
		}
		$data = ['title' => $title, 'content' => $content, 'name' => $name, 'time' => $time];
//       return  response()->json(['code'=>200,'msg'=>'请求成功','data'=>['title'=>$title,'content'=>$content,'name'=>$name,'time'=>$time]]);
		echo $request->input('callback') . '(' . json_encode($data) . ')';
	}

	public function resume(Request $request, $ids) {
		$id_arr = \Hashids::decode($ids);
		if (empty($ids) || empty($id_arr[0])) {
			return response($request->input('callback') . '(' . json_encode(['code' => 500, 'msg' => '参数为空或无效!']) . ')');
		}
		$id = $id_arr[0];
		$model = \App\Models\Resume::find($id);
		if (!empty($model)) {
			if ($model->status == 1) {
				return response($request->input('callback') . '(' . json_encode(['code' => 500, 'msg' => '该简历已经被删除！']) . ')');
			}
			$staff = \App\Models\Staff::where(['user_id' => $model->owner_id, 'company_id' => $model->company_id, 'status' => 0])->first();
			if (!empty($staff)) {
				$model['own_name'] = $staff->name;
			} else {
				$model['own_name'] = '';
			}
			$position = \App\Models\Position::where(['company_id' => $model->company_id, 'status' => 0])->first();
			if (!empty($position)) {
				$model['position_name'] = $position->name;
			} else {
				$model['position_name'] = '';
			}
			$attachment = $model->attachment;
			if (!empty($attachment)) {
				$ext = substr($attachment, strrpos($attachment, '.') + 1);
				if (in_array(strtolower($ext), ['png', 'jpg'])) {
					$attachment = 'api/v1/resume/upload?file=' . $model->attachment;
				}
			}
			$model['attachment'] = $attachment;
			$data['resume'] = $model;
			$data['job'] = \App\Models\Job::where(['resume_id' => $id, 'status' => 0])->orderBy('id', 'desc')->get();
			$data['item'] = \App\Models\Item::where(['resume_id' => $id, 'status' => 0])->orderBy('id', 'desc')->get();
			$data['edu'] = \App\Models\Education::where(['resume_id' => $id, 'status' => 0])->orderBy('id', 'desc')->get();
			return response($request->input('callback') . '(' . json_encode($data) . ')');
		}
		return response($request->input('callback') . '(' . json_encode(['code' => 500, 'msg' => '未发现该对象']) . ')');
	}
//	职位\(^o^)/~
	public function position(Request $request) {
		$positionId = $request->input('id');
		$type = $request->input('type') ?? 1;
		$posInfo = DB::table('positions')->find($positionId);
		if ($type == 1) {
			echo $request->input('callback') . '(' . json_encode($posInfo) . ')';
		} else {
			return response()->json(['code' => 200, 'msg' => '操作成功', 'data' => ['posInfo' => $posInfo]]);
		}

	}
//    企业招聘网站配置查询，职位查询
	public function recruitmentInfo(Request $request) {
		$cid = $request->input('id');
		$page = $request->input('page') ?? 1;
		$name = $request->input('name') ?? "";
		$cmpInfo = DB::table('configuration')->where('company_id', $cid)->select('id', 'url_name as urlName', 'company_name as companyName', 'publicity', 'logo', 'banner')->first();
		if (empty($cmpInfo)) {
            $cmpInfo = [];
		}
		if ($page == 1) {
			$positionInfo = DB::table('positions')
                ->join('users','positions.user_id','=','users.id')
				->where(['positions.company_id' => $cid, 'positions.is_use' => 1,'positions.status'=>0])
				->skip(0)
				->take(6)
                ->select('positions.*')
				->orderBy('updated_at', 'desc')
				->get();
			$number = DB::table('positions')
                ->join('users','positions.user_id','=','users.id')
                ->where(['positions.company_id' => $cid, 'positions.is_use' => 1,'positions.status'=>0])->count();
		} else {
			$query = DB::table('positions')
                ->join('users','positions.user_id','=','users.id')
                ->where(['positions.company_id' => $cid, 'positions.is_use' => 1,'positions.status'=>0]);
			if ($name == 0 || !empty($name)) {
				$query = $query->where('positions.name', 'like', '%' . $name . '%');
			}
			$positionInfo = $query->orderBy('positions.updated_at', 'desc')
                ->select('positions.*')
				->get();
			$number = $query->count();
		}
		if ($number > 6) {
			$number = 1;
		} else {
			$number = 0;
		}
		return response()->json(['code' => 200, 'msg' => '操作成功', 'data' => ['cmpInfo' => $cmpInfo, 'positions' => $positionInfo, 'number' => $number]]);
//        return response($request->input('callback') . '(' . json_encode(['code' => 200, 'msg' => '操作成功','data'=>['cmpInfo'=>$cmpInfo,'positions'=>$positionInfo]]) . ')');
	}
	public function testEmail(Request $request) {
		\Log::info('测试邮件发送');
		$content = "这是一封测试邮件";
		$sub = 'test';
		$to = $request->input('to');
		$mobile = $request->input('mobile');
		$userInfo = User::where('mobile', $mobile)->first();
		\Log::info('user_info' . json_encode($userInfo));
		if(!$this->getDevice()){
		    $userInfo->company_id = $userInfo->appcompany_id;
        }
		$email = DB::table('email_sets')->where('company_id', $userInfo->company_id)->first();
		\Log::info('email' . json_encode($email));
		if (empty($email) || (!empty($email) && empty($email->user_name))) {
			return response()->json(['code' => 400, 'msg' => '邮箱未配置', 'data' => ""]);
		}
		$message = '这是一封测试邮件';
		$subject = '李大哥';
//        $result = $this->sendMail($content, $to, $sub);
//        return $result;
		$this->dispatch(new SendEmail($userInfo, $message, $to, $subject));
		return response()->json(['code' => 200, 'msg' => '操作成功', 'data' => '']);
	}
	public function test(Request $request){
        $config = Config::get('info.message_config');
        $easySms = new EasySms($config);
        $mobile = $request->input('mobile');
        $code = '1111';
        try {
            $result = $easySms->send($mobile, [
                'content' => '您的验证码${code}，该验证码5分钟内有效，请勿泄漏于他人！',
                'template' => 'SMS_126570108',
                'data' => [
                    'code' => $code,
                ],
            ]);
        } catch (NoGatewayAvailableException $e) {
            dd($e);
            return response()->json(['code' => 200, 'msg' => '短信发送失败', 'data' => '']);
        }
        return response()->json($result);
    }
}
